<?php

namespace Kollway\CodeGenerator\Generators;

class ModelGenerator extends Generator
{
    public function generateModelString()
    {
        $model = <<<MODEL
<?php

namespace App\Model;

/**
 * @property integer \$id
 */
class {$this->model_name} extends BaseModel
{
    protected \$table = '$this->table';\n\n
MODEL;

        $model .= $this->generateFillable();
        $model .= $this->generateRequiredRules();
        $model .= $this->generateAttributes();

        $model .= <<<MODEL
\n}
MODEL;

        $this->content = $model;

        return $model;
    }

    private function generateFillable()
    {
        $string = <<<FILLABLE
    protected \$fillable = [\n
FILLABLE;

        $fields = array_column($this->column_info, 'field');
        $fields = array_diff($fields, ['id']);
        $string .= $this->implodeFieldsToString($fields);

        $string .= <<<FILLABLE
    ];\n
FILLABLE;

        return $string;
    }

    // 一行最多显示 6 个数组项
    // 一行最多 6 个字段
    private function implodeFieldsToString($fields)
    {
        $string = '        ';

        foreach ($fields as $key => $item) {
            if ($key % 6 == 0) {
                $string .= "\n        ";
            }

            $string .= "'$item', ";
        }

        $string .= "\n";

        return $string;
    }

    // 必填字段
    private function generateRequiredRules()
    {
        $required_fields = $this->required_fields;

        if ($required_fields) {
            $string = <<<ATTR
\n    protected \$rules = [\n
ATTR;

            if (is_string($required_fields)) {
                $required_fields = [$required_fields];
            }

            foreach ($required_fields as $column) {
                $string .= <<<RULE
        '{$column}' => 'required',\n
RULE;
            }

            $string .= <<<ATTR
    ];\n\n
ATTR;

            return $string;
        }

        return "\n";
    }

    // 属性列表
    private function generateAttributes()
    {
        $string = <<<ATTR
    protected \$attribute = [

ATTR;

        foreach ($this->column_info as $column) {
            if (in_array($column['field'], ['id', 'status', 'sort_index', 'is_deleted', 'create_time', 'update_time'])) {
                continue;
            }

            $string .= <<<ATTR
        '{$column['field']}' => '{$column['comment']}',\n
ATTR;
        }

        $string .= <<<ATTR
    ];
ATTR;
        return $string;
    }
}